import numpy as np
from tensorflow import keras
from dataset.MCsvDataset import MCsvDataset
from model.MDecisionModel import MDecisionModel
import matplotlib.pyplot as plt
from dataset.Utils import Utils

learning_rate = 0.02
kernel_initializer = keras.initializers.glorot_normal
activation = keras.activations.sigmoid
day_shape = (10, 6)
min_shape = (120, 6)
epochs = 100

modelCreator = MDecisionModel(activation=activation,
                              kernel_initializer=kernel_initializer,
                              learning_rate=learning_rate,
                              name="min_decision_m999",
                              day_shape=day_shape,
                              min_shape=min_shape,
                              epochs=epochs)
model = modelCreator.create_model()
model.summary()

# 打印model 结构图
keras.utils.plot_model(model, show_shapes=True, rankdir="LR")

day_csv_url = "/Users/aloudata/Downloads/train_data/M999/M9999-DAY.XDCE.csv"
min_csv_url = "/Users/aloudata/Downloads/train_data/M999/M9999.XDCE.csv"
dataset_reader = MCsvDataset(day_csv=day_csv_url, day_lookup=10, min_csv=min_csv_url, min_lookup=120)
day_dataset, min_dataset, target_dataset = dataset_reader.read_min_and_day(normalization=True,
                                                                           # ds_cnt=20000,
                                                                           stable_threshold_unit=1,
                                                                           start_code="M2005")

total_cnt = len(day_dataset)
val_cnt = int(total_cnt * 0.05)
train_cnt = total_cnt - val_cnt

train_day_ds = day_dataset[0:train_cnt]
train_min_ds = min_dataset[0:train_cnt]
train_target_ds = target_dataset[0:train_cnt]

val_day_ds = day_dataset[train_cnt:]
val_min_ds = min_dataset[train_cnt:]
val_target_ds = target_dataset[train_cnt:]

history = modelCreator.train_model(train_data={
    "day-input": train_day_ds,
    "min-input": train_min_ds
},
    train_target=train_target_ds,
    val_data={
        "day-input": val_day_ds,
        "min-input": val_min_ds
    },
    val_target=val_target_ds
)


def visualize_loss(history, title):
    loss = history.history["loss"]
    val_loss = history.history["val_loss"]
    epochs = range(len(loss))
    plt.figure()
    plt.plot(epochs, loss, "b", label="Training loss")
    plt.plot(epochs, val_loss, "r", label="Validation loss")
    plt.title(title)
    plt.xlabel("Epochs")
    plt.ylabel("Loss")
    plt.legend()
    plt.show()


visualize_loss(history, "Training and Validation Loss")

predict_day_ds = day_dataset[total_cnt - 50:]
predict_min_ds = min_dataset[total_cnt - 50:]
predict_target_ds = target_dataset[total_cnt - 50:]

result = model.predict({
    "day-input": predict_day_ds,
    "min-input": predict_min_ds
})

print(f'{result}')

right_cnt = 0
for i in range(len(result)):
    if Utils.is_predict_right(result[i], target_dataset[i]):
        right_cnt = right_cnt + 1

print(f"Predict accuracy: {round(right_cnt * 100 / len(result), 2)}%")
